<template>
  <a-card :bordered='false'>
    <!-- 查询区域 -->
    <search :config='searchConfig' @getHeight='getHeight' @search='search' />
    <!-- table区域-begin -->
    <div class='page_table'>
      <vxe-grid
        ref='xGrid'
        v-bind='vexConfig'
        :align='left'
        :border='true'
        :checkbox-config='checkboxConfig'
        :columns='columns'
        :data='dataSource'
        :height='pageHeight-seachHeight-90'
        :loading='loading'
        :resizable='true'
        :showOverflow='true'
        :toolbar-config='tableToolbar'
        size='mini'
        @checkbox-change='selectChangeEvent'
        @checkbox-all='selectChangeEvent'
      >
        <template #toolbar_buttons>
          <div class='table-operator'>
            <a-button type="primary"  @click="createObj.visible=true">创建流程模型</a-button>
          </div>
        </template>
        <template #revision='{ row,record }'>
          v.{{ row.version_ }}
        </template>
        <template #metaInfo='{ row,record }'>
          <j-ellipsis :length='10' :value='row.metaInfo.description' />
        </template>
        <template #action='{ row:record }'>
          <a v-has="'terminal:update'" @click='deployment(record)'>发布</a>
          <a-divider type='vertical' />
          <a-dropdown>
            <a class='ant-dropdown-link'>更多
              <a-icon type='down' />
            </a>
            <a-menu slot='overlay'>
              <a-menu-item>
                <a href='javascript:' @click='updatelc(record.id)'>设计流程</a>
              </a-menu-item>
              <a-menu-item>
                <a @click="showResource(record)" >查看流程图</a>
              </a-menu-item>
              <a-menu-item>
                <a @click="seeHistory(record)">历史版本</a>
              </a-menu-item>
              <a-menu-item>
                <a-popconfirm title="确定删除吗?" @confirm="() => handleDelete(record.id)">
                  <a>删除</a>
                </a-popconfirm>
              </a-menu-item>
            </a-menu>
          </a-dropdown>
        </template>

        <template #pager>
          <vxe-pager :currentPage.sync='ipagination.current'
                     :layouts="['Total', 'PrevJump', 'PrevPage', 'Number', 'NextPage', 'NextJump','Sizes', 'FullJump']" :page-size.sync='ipagination.pageSize'
                     :pageSizes='ipagination.pageSizeOptions'
                     :total='ipagination.total' @page-change='handlePageChange'>
          </vxe-pager>
        </template>
      </vxe-grid>
    </div>
    <!-- table区域-end -->
    <a-modal
      :confirmLoading='createObj.confirmLoading'
      :visible='createObj.visible'
      title='创建模型'
      @cancel='createObj.visible = false'
      @ok='createObjOk'
    >
      <div>
        模型名称：
        <a-input v-model='createObj.name' placeholder='输入模型名称'></a-input>
        <br />
        模型Key：
        <a-input v-model='createObj.key' placeholder='输入模型Key'></a-input>
        <br />
        模型描述：
        <a-textarea v-model='createObj.description' :rows='4' placeholder='输入模型描述' />
      </div>
    </a-modal>
    <j-modal
      :footer='null'
      fullscreen
      :maskClosable='false'
      :visible='updateObj.visible' style='top: 20px;'
      switchFullscreen
      title='设计模型'
      width='90%'
      @cancel='cancelUpdate'
    >
      <iframe :src='iframUrl' frameborder='0' height='100%' scrolling='auto' style='background-color: #fff;'
              width='100%'></iframe>
    </j-modal>
    <!--查看图片-->
    <a-modal
      :title="viewTitle" width="90%"
      :visible="viewImage" :footer="null"
      @cancel="viewImage = false"
    >
      <div style="min-height: 400px">
        <img :src="diagramUrl" :alt="viewTitle">
      </div>
    </a-modal>
    <policys ref="policysModal" v-bind="policysData"></policys>
  </a-card>

</template>

<script>
import { filterObj } from '@/utils/util'
import { PageListMixin } from '@/mixins/PageListMixin'
import JEllipsis from '@/components/cn-form/JEllipsis'
import { postAction, getAction, downFile } from '@/api/manage'
import policys from '@comp/cn-components/Policys'
export default {
  name: 'ModelList',
  mixins: [PageListMixin],
  components: {
    JEllipsis,policys
  },
  data() {
    return {
      //查询区域
      searchConfig: [
        {
          type: 'input',
          name: 'name_',
          placeholder: '模型名称'
        }
      ],
      /*流程设计器连接*/
      iframUrl: '',
      /*新增流程框参数*/
      createObj: {
        visible: false,
        confirmLoading: false
      },
      /*设计流程框参数*/
      updateObj: {
        visible: false,
        confirmLoading: false
      },
      /*流程图参数*/
      viewImage:false,
      viewTitle:"",
      diagramUrl:"",

      description: '这是流程模型列表页面',
      // 查询条件
      queryParam: {
        createTimeRange: [],
        keyWord: ''
      },
      tabKey: '1',
      // 表头
      columns: [
        {
          type: 'checkbox',
          width: 60,
          fixed: 'left'
        },
        {
          title: '模型id',
          minWidth: 80,
          field: 'id'
        },
        {
          title: '模型名称',
          minWidth: 80,
          field: 'name_'
        },
        {
          title: '模型key',
          minWidth: 80,
          field: 'key_',
        },
        {
          title: '状态',
          minWidth: 80,
          field: 'processStatusName',
        },
        {
          title: '版本',
          minWidth: 80,
          field: 'revision_',
          slots: {
            default: 'revision'
          }
        },
        {
          title: '备注描述',
          minWidth: 80,
          field: 'metaInfo',
          slots: {
            default: 'metaInfo'
          }
        },
        {
          title: '创建时间',
          minWidth: 80,
          field: 'createTime_',
          // sorter:true
        },
        {
          title: '最后更新时间',
          minWidth: 120,
          field: 'lastUpdateTime_',
        },
        {
          title: '操作',
          minWidth: 150,
          field: 'action',
          slots: {
            default: 'action'
          }
        }
      ],
      labelCol: {
        xs: { span: 1 },
        sm: { span: 2 }
      },
      wrapperCol: {
        xs: { span: 10 },
        sm: { span: 16 }
      },
      url: {
        list: window._CONFIG['domianActivitiURL'] + '/activiti/models/modelListData',
        delete: window._CONFIG['domianActivitiURL'] + '/activiti/models/delete',
        deployment: window._CONFIG['domianActivitiURL'] + '/activiti/models/deployment',
        create: window._CONFIG['domianActivitiURL'] + '/activiti/models/newModel',
        update: window._CONFIG['domianActivitiURL'] + '/designController/editor?modelId=',
        img: window._CONFIG['domianActivitiURL']+"/designController/showPic",
      }
    }
  },
  computed: {
    policysData() {
      return {
        title: '历史版本',
        width: `${50}%`,
        rowKey: 'poolCode',
        tableShowSelect:false,
        way: 'post',
        tableUrl: window._CONFIG['domianActivitiURL'] + '/activiti/models/listByKey',
        tableColums: [
          {
            title: '版本',
            align: 'center',
            dataIndex: 'version'
          },
          {
            title: '资源名称',
            align: 'center',
            dataIndex: 'name'
          },
          {
            title: '流程图名称',
            align: 'center',
            dataIndex: 'resourceName'
          },
          {
            title: '部署ID',
            align: 'center',
            dataIndex: 'deploymentId'
          },
          {
            title: '操作',
            align: 'center',
            dataIndex: 'productName',
            customRender: (value, row, index) => {
              let vm = this
              let child = vm.$createElement('a', {
                domProps: {
                  innerHTML: '详情',
                  href : window._CONFIG['domianActivitiURL'] + '/designController/showBpmn?deploymentId='+row.deploymentId,
                  target:"_blank"
                },
              })
              const obj = {
                children: child,
                attrs: {}
              }
              return obj
            }
          },
        ],
        haveSelect:{},
        multiple: false
      }
    },

  },
  methods: {
    seeHistory(cord){
      let params = {
        key:cord.key_
      }
      this.$refs.policysModal.edit(params)
    },
    /*创建流程*/
    createObjOk(e) {
      this.createObj.confirmLoading = true
      let _this =  this;
      postAction(_this.url.create,_this.createObj).then((res) => {
        if (res.success) {
          _this.$message.success(res.message)
        } else {
          _this.$message.error(res.message)
        }
        _this.createObj.visible = false
        _this.createObj.confirmLoading = false
        _this.loadData()
      })


    },
    /*修改流程*/
    updatelc(id) {
      var _this = this
      this.$message
        .loading('稍等。。。', 0.8)
        .then(() => {
          _this.createObj.confirmLoading = true
          _this.iframUrl = `${_this.url.update}${id}`
          _this.updateObj.visible = true
          _this.createObj.confirmLoading = false
        })
    },
    cancelUpdate() {
      var _this = this
      this.$confirm({
        title: '关闭前请确认已保存修改?',
        content: '关闭后未保存的修改将丢失！',
        okText: '确认关闭',
        okType: 'danger',
        cancelText: '再看看',
        onOk() {
          _this.updateObj.visible = false
          _this.loadData()
        },
        onCancel() {
          console.log('Cancel')
        }
      })

    },
    /*发布流程*/
    deployment(row) {
      var _this = this
      var id = row.id
      var name = row.name_

      this.$confirm({
        title: '确认部署流程?',
        content: `确认部署流程：${name}`,
        onOk() {
          _this.loading = true
          getAction(_this.url.deployment +'?id='+ id).then((res) => {
            if (res.success) {
              _this.$message.success(res.message)
            } else {
              _this.$message.error(res.message)
            }
            _this.loading = false
            _this.loadData()
          })
        },
        onCancel() {
          _this.loading = false
        }
      })

    },
    handleTableChange(pagination, filters, sorter) {
      //分页、排序、筛选变化时触发
      //TODO 筛选
      if (Object.keys(sorter).length > 0) {
        this.isorter.column = sorter.field
        this.isorter.order = 'ascend' == sorter.order ? 'asc' : 'desc'
      }
      this.ipagination = pagination
      // this.loadData();
    },
    loadData(arg) {
      if (!this.url.list) {
        this.$message.error('请设置url.list属性!')
        return
      }
      //加载数据 若传入参数1则加载第一页的内容
      if (arg === 1) {
        this.ipagination.current = 1
      }
      var params = this.getQueryParams()//查询条件
      this.loading = true
      postAction(this.url.list, params).then((res) => {
        if (res.success) {
          let records = res.result.records || []
          this.dataSource = records
          records.forEach(item => {
             let infom = item.metaInfo_;
             if (infom!=null && infom!=undefined){
               item.metaInfo = JSON.parse(infom);
             }
          })
          this.ipagination.total = records.length
        }
        if (res.code === 510) {
          this.$message.warning(res.message)
        }
        this.loading = false
      })
    },
    getQueryParams() {
      var param = Object.assign({}, this.queryParam, this.isorter)
      delete param.createTimeRange // 时间参数不传递后台
      return filterObj(param)
    },

    // 重置
    searchReset() {
      var that = this
      var logType = that.queryParam.logType
      that.queryParam = {} //清空查询区域参数
      that.queryParam.logType = logType
      that.loadData(this.ipagination.current)
    },
    onDateChange: function(value, dateString) {
      console.log(dateString[0], dateString[1])
      this.queryParam.createTime_begin = dateString[0]
      this.queryParam.createTime_end = dateString[1]
    },
    onDateOk(value) {
      console.log(value)
    },
    /*查看流程图片*/
    showResource(row) {
      this.viewTitle = "流程图片预览(" + row.name_ + ")";
      this.diagramUrl = `${this.url.img}?deploymentId=${row.deploymentId_}`;
      this.viewImage = true;
    },
  }
}
</script>
<style scoped>
@import '~@assets/less/common.less';
</style>